import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', () => {
  const isLoggedIn = ref(false)
  const userInfo = ref({
    username: '',
    avatar: ''
  })

  const login = (username, avatar) => {
    isLoggedIn.value = true
    userInfo.value = {
      username,
      avatar: avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    }
    localStorage.setItem('auth', JSON.stringify(userInfo.value)) // 持久化存储
  }

  const logout = () => {
    isLoggedIn.value = false
    userInfo.value = { username: '', avatar: '' }
    localStorage.removeItem('auth')
  }

  // 初始化时从本地存储加载
  const init = () => {
    const savedAuth = localStorage.getItem('auth')
    if (savedAuth) {
      userInfo.value = JSON.parse(savedAuth)
      isLoggedIn.value = true
    }
  }

  init() // 立即执行初始化

  return { isLoggedIn, userInfo, login, logout }
})
